package com.zhou.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.zhou.common.to.es.SkuEsModel;
import com.zhou.gulimall.search.config.GulimallESConfig;
import com.zhou.gulimall.search.constant.EsConstant;
import com.zhou.gulimall.search.service.MallSearchService;
import com.zhou.gulimall.search.vo.SearchParam;
import com.zhou.gulimall.search.vo.SearchResult;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class MallSearchServiceImpl implements MallSearchService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public SearchResult search(SearchParam searchParam) {
        //1.动态构建出查询需要的dsl语句


        //构建返回对象
        SearchResult result = null;
        //2.准备检索请求
        //SearchRequest searchRequest = new SearchRequest();
        SearchRequest searchRequest = buildSearchRequest(searchParam);
        try {
            //2.1执行检索请求
            SearchResponse response = restHighLevelClient.search(searchRequest, GulimallESConfig.COMMON_OPTIONS);

            //3.分析响应数据，封装成需要的格式
            result = buildSearchResult(response,searchParam);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return result;
    }

    /**
     * 构建检索请求
     * 模糊匹配，过滤（按照属性，分类，品牌，价格区间，库存），排序，分页，高亮，聚合分析
     * @return
     *
     */
    private SearchRequest buildSearchRequest(SearchParam searchParam) {
        //构建dsl语句
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        //1.Query模糊匹配，过滤（按照属性，分类，品牌，价格区间，库存）
        //bool Query通过工具类QueryBuilders构建一个boolQuery();
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //1.1 bool-must做模糊匹配
        if (!StringUtils.isEmpty(searchParam.getKeyword())){
            boolQueryBuilder.must(QueryBuilders.matchQuery("skuTitle",searchParam.getKeyword()));
        }
        //1.2 bool-filter-getCatalog3Id 分类
        if (searchParam.getCatalog3Id() != null){
            boolQueryBuilder.filter(QueryBuilders.termQuery("catalogId",searchParam.getCatalog3Id()));
        }
        //1.2.1 bool-filter-brandId 品牌
        if (searchParam.getBrandId() != null && searchParam.getBrandId().size() > 0){
            boolQueryBuilder.filter(QueryBuilders.termsQuery("brandId",searchParam.getBrandId()));
        }
        //1.2.2 bool-filter-attrs 所有指定的属性（嵌入式nested）
        if (searchParam.getAttrs() != null && searchParam.getAttrs().size() > 0){
            for (String attrStr : searchParam.getAttrs()) {
                //属性（嵌入式检索）检索条件
                BoolQueryBuilder nestedBoolQuery = QueryBuilders.boolQuery();

                String[] s = attrStr.split("_");
                String attrId = s[0];//检索的属性
                String[] attrValues = s[1].split(":");//属性检索的值
                nestedBoolQuery.must(QueryBuilders.termQuery("attrs.attrId",attrId));
                nestedBoolQuery.must(QueryBuilders.termsQuery("attrs.attrValue",attrValues));
                //构建嵌入式Query查询。每一条属性检索都要生成一个nestedQuery
                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", nestedBoolQuery, ScoreMode.None);
                boolQueryBuilder.filter(nestedQuery);
            }
        }

        //1.2.3 bool-filter-hasStock 库存：：1查询有库存。0或者不传值则查询全部
        if (searchParam.getHasStock()!=null){
            boolQueryBuilder.filter(QueryBuilders.termQuery("hasStock",searchParam.getHasStock()==1));
        }

        //1.2.4 bool-filter-skuPrice 价格区间：
        if (!StringUtils.isEmpty(searchParam.getSkuPrice())){
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");
            String[] s = searchParam.getSkuPrice().split("_");
            if (s.length == 2){
                //区间a->b
                rangeQuery.gte(s[0]).lte(s[1]);
            }else if (s.length == 1){
                if(searchParam.getSkuPrice().startsWith("_")){
                    //小于等于
                    rangeQuery.lte(s[0]);
                }
                if (searchParam.getSkuPrice().endsWith("_")){
                    //大于等于
                    rangeQuery.gte(s[0]);
                }
            }
            boolQueryBuilder.filter(rangeQuery);

        }

        //1.3把所有的检索条件boolQueryBuilder封装
        sourceBuilder.query(boolQueryBuilder);
        //2.sort排序，
        //sort=hotscore_desc
        //TODO 一次只能一个排序条件
        if (!StringUtils.isEmpty(searchParam.getSort())){
            String sort = searchParam.getSort();
            String[] s = sort.split("_");
            SortOrder order = s[1].equalsIgnoreCase("asc")? SortOrder.ASC:SortOrder.DESC;
            sourceBuilder.sort(s[0],order);

        }
        //3.分页from。size
        //from=(页码-1)*每页的size
        sourceBuilder.from((searchParam.getPageNum()-1)*EsConstant.PRODUCT_PAGESIZE);
        sourceBuilder.size(EsConstant.PRODUCT_PAGESIZE);
        //4.高亮highlight 只有前端传递关键字查询时才会进行高亮操作
        if (!StringUtils.isEmpty(searchParam.getKeyword())){
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle");
            highlightBuilder.preTags("<b style='color:red'>");
            highlightBuilder.postTags("</b>");
            sourceBuilder.highlighter(highlightBuilder);
        }
        //5。聚合分析
        //5.1 品牌聚合brand_agg
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg");
        brand_agg.field("brandId").size(50);
        //5.1.2品牌聚合的子聚合
        /** "aggs":"brand_name_agg";"brand_img_agg" */
        brand_agg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
        brand_agg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));
        sourceBuilder.aggregation(brand_agg);
        //5.2分类聚合catalog_agg
        TermsAggregationBuilder catalog_agg = AggregationBuilders.terms("catalog_agg");
        catalog_agg.field("catalogId").size(20);
        //5.2.2分类聚合的子聚合catalog_name_agg
        catalog_agg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1));
        sourceBuilder.aggregation(catalog_agg);

        //5.3 属性聚合attr_agg聚合,嵌入式聚合nested
        NestedAggregationBuilder nested = AggregationBuilders.nested("attr_agg","attrs");
        //5.3.2 属性聚合的子聚合attr_id_agg ==》聚合出所有属性的id
        TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId").size(50);
        //5.3.3 属性聚合子聚合attr_id_agg的子聚合
        /**  "aggs":"attr_name_agg";"attr_value_agg" */
        //"attr_name_agg"聚合==》当前attrId对应的名字 //"attr_value_agg"聚合==》当前attrId所有存在属性的值value
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(1));
        //将属性聚合的子聚合attr_id_agg放入属性聚合nested(attr_agg)
        nested.subAggregation(attr_id_agg);
        //将属性聚合nested(attr_agg)放入sourceBuilder
        sourceBuilder.aggregation(nested);

        //打印动态生成的dsl语句
        String s = sourceBuilder.toString();
        System.out.println("构建的dsl语句："+s);
        SearchRequest searchRequest = new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, sourceBuilder);

        return searchRequest;
    }

    /**
     * 构建结果数据
     * @param response
     * @return
     */
    private SearchResult buildSearchResult(SearchResponse response,SearchParam searchParam) {
        SearchResult result = new SearchResult();
        //从命中的结果中获取数据
        SearchHits hits = response.getHits();
        //准备一个List<SkuEsModel>用于存储商品信息
        List<SkuEsModel> esModelList = new ArrayList<>();


        //1.返回的所有查询到的商品
        //result.setProducts();
        SearchHit[] hitsHits = hits.getHits();
        if (hits.getHits()!=null && hits.getHits().length>0){
            for (SearchHit hitsHit : hitsHits) {
                String sourceAsString = hitsHit.getSourceAsString();//获取string商品类型数据
                SkuEsModel esModel = JSON.parseObject(sourceAsString, SkuEsModel.class);
                esModelList.add(esModel);
            }
        }
        result.setProducts(esModelList);

        //2.当前所有商品涉及到的所有属性信息
        //result.setAttrVos();
        List<SearchResult.AttrVo> attrVos = new ArrayList<>();
        ParsedNested attr_agg = response.getAggregations().get("attr_agg");
        ParsedLongTerms attr_id_agg = attr_agg.getAggregations().get("attr_id_agg");
        for (Terms.Bucket bucket : attr_id_agg.getBuckets()) {
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
            //当前属性id
            attrVo.setAttrId(bucket.getKeyAsNumber().longValue());
            //当前属性id对应的name
            attrVo.setAttrName(bucket.getAggregations().get("attr_name_agg").getName());
            bucket.getAggregations().get("attr_value_agg");

        }


        //3.当前商品所涉及到的所有品牌信息
        //result.setBrands();
        List<SearchResult.BrandVo> brandVoList = new ArrayList<>();
        ParsedLongTerms brand_agg = response.getAggregations().get("brand_agg");
        List<? extends Terms.Bucket> brand_aggBuckets = brand_agg.getBuckets();
        for (Terms.Bucket brand_aggBucket : brand_aggBuckets) {
            SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
            //品牌id BrandId
            long l = brand_aggBucket.getKeyAsNumber().longValue();
            brandVo.setBrandId(l);
            //品牌name BrandName
            ParsedStringTerms brand_name_agg = brand_aggBucket.getAggregations().get("brand_name_agg");

            brandVo.setBrandName(brand_name_agg.getBuckets().get(0).getKeyAsString());
            //品牌img BrandImg
            //TODO 顺便查看一下Aggregation类型能不能接收到response
            ParsedStringTerms brand_img_agg = brand_aggBucket.getAggregations().get("brand_img_agg");
            brandVo.setBrandImg(brand_img_agg.getBuckets().get(0).getKeyAsString());

            brandVoList.add(brandVo);
        }


        //4.当前商品所涉及到的所有的分类信息
        //result.getCatalogVos();
        ParsedLongTerms catalog_agg = response.getAggregations().get("catalog_agg");
        //准备一个List<SearchResult.CatalogVo>集合存放分类信息
        List<SearchResult.CatalogVo> catalogVoList = new ArrayList<>();
        List<? extends Terms.Bucket> buckets = catalog_agg.getBuckets();
        for (Terms.Bucket bucket : buckets) {
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
            //分类id
            String keyIdAsString = bucket.getKeyAsString();
            catalogVo.setAttrId(Long.parseLong(keyIdAsString));
            //分类name 子聚合
            ParsedStringTerms catalog_name_agg = bucket.getAggregations().get("catalog_name_agg");
            String keyNameAsString = catalog_name_agg.getBuckets().get(0).getKeyAsString();
            catalogVo.setAttrName(keyNameAsString);

            catalogVoList.add(catalogVo);
        }
//==============================================================================
        //以上信息在聚合信息中获取

        //5.分页信息-页码
        //result.getPageNum()
        result.setPageNum(searchParam.getPageNum());
        //分页信息-总记录数
        //result.setTotal();
        long total = hits.getTotalHits().value;
        //分页信息-总页码
        //result.setTotalPages();======信息总条数/每页数量(常量EsConstant.PRODUCT_PAGESIZE)，有余数加1
        int totalPages = (int)total%EsConstant.PRODUCT_PAGESIZE == 0?(int) total/EsConstant.PRODUCT_PAGESIZE:((int)total/EsConstant.PRODUCT_PAGESIZE+1);
        result.setTotalPages(totalPages);

        return null;
    }

}
